package com.gt.quality.controller;

import cn.dev33.satoken.annotation.SaIgnore;
import cn.hutool.core.text.CharSequenceUtil;
import cn.hutool.json.JSONUtil;
import com.gt.quality.base.pojo.Resp;
import com.gt.quality.system.service.LocalDatabaseProxy;
import com.gt.quality.system.service.ZhiPuAiProxyService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.task.TaskExecutor;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import reactor.core.publisher.Flux;

import java.util.List;
import java.util.Map;

/**
 * 万里悲秋常作客,百年多病独登台
 *
 * @author : makeJava
 */
@RestController
@RequestMapping("/ai")
@Slf4j
@SaIgnore
@Tag(name = "AI能力接口")
public class ZhiPuAiController {

    @Resource
    private ZhiPuAiProxyService zhiPuAiProxyService;

    @Resource
    private LocalDatabaseProxy localDatabaseProxy;

    @Resource(name = "threadPoolTaskExecutor")
    TaskExecutor taskExecutor;


    /**
     * AI对话式分析同步调用
     */
    @RequestMapping("/zhi_pu_qa")
    @Operation(summary = "对话式分析")
    public String testInvoke(@RequestParam(value = "question", defaultValue = "2026年创建的用户信息有哪些?", required = false) String question, @RequestParam(value = "dbName", defaultValue = "test_admin_123", required = false) String dbName) {
        // 获取指定数据库的所有表名和表注释
        String tablesAndComments = localDatabaseProxy.getTablesAndComments(dbName);
        String notFindMsg = "知识库未找到相关信息";
        if (CharSequenceUtil.isBlank(tablesAndComments)) {
            return notFindMsg;
        }
        // 询问Ai获取指定问题和表的相似的相关的表信息
        String tableInfosJson = zhiPuAiProxyService.handlerAiQuestion(tablesAndComments, question, false);
        if (CharSequenceUtil.isBlank(tableInfosJson)) {
            return notFindMsg;
        }
        // 处理AI回答的数据获取实际用的表
        String tableNames = zhiPuAiProxyService.parseTableFromResponse(tableInfosJson);
        if (CharSequenceUtil.isBlank(tableNames)) {
            return notFindMsg;
        }
        // 根据表名称--获取对应的表结构的列名和注释
        String columnsAndComments = localDatabaseProxy.getTableDdl(dbName, tableNames);
        // 将问题询问AI关联到那几张表--定位
        String result = zhiPuAiProxyService.handlerAiQuestion(columnsAndComments, question, true);
        if (result == null) {
            return "接口调用失败，请检查日志!";
        }
        // 解析获取到的SQL
        String sql = zhiPuAiProxyService.parseSqlFromResponse(result);
        if (sql == null) {
            return "解析SQL失败，请检查AI返回的内容!";
        }
        // 调用JDBC连接执行该SQL拿到结果
        List<Map<String, Object>> resultList = localDatabaseProxy.executeSql(sql);

        // 将结果转换为JSON字符串返回
        return JSONUtil.toJsonStr(resultList);
    }


    /**
     * 事件流---式调用问答
     */
    @RequestMapping(value = "/zhi_pu_say", method = {RequestMethod.GET, RequestMethod.POST}, produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    @Operation(summary = "流式问答")
    public Flux<String> testSseInvoke(@RequestParam(value = "question", defaultValue = "2025年国家GPD第一季度的详细情况?", required = false) String question) {
        log.info("question:{}", question);
        return zhiPuAiProxyService.streamInvoke(question);
    }

    /**
     * 事件流---式调用问答
     */
    @RequestMapping(value = "/jsonToSay", method = RequestMethod.POST, produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    @Operation(summary = "流式问答")
    public Flux<String> jsonToSay(@RequestBody String question) {
        return zhiPuAiProxyService.streamInvoke(question);
    }


    /**
     * 智普AI文件上传解析
     *
     * @param file file
     * @return r
     */
    @PostMapping(value = "/zhi_pu_upload")
    @Operation(summary = "智普AI文件上传解析")
    public Resp<Object> uploadFile(@RequestParam("file") MultipartFile file) {
        return Resp.ok(zhiPuAiProxyService.fileHandler(file));
    }

    /**
     * 智普AI文件上传解析
     *
     * @return r
     */
    @GetMapping(value = "/async")
    @Operation(summary = "异步虚拟线程执行")
    public Resp<Object> threadExecutor() {
        taskExecutor.execute(() -> {
            String name = Thread.currentThread().getName();
            System.out.println(name + "Hello 虚拟线程");
        });
        return Resp.ok();
    }


    /**
     * 智普AI 视频接口
     *
     * @return r
     */
    @GetMapping(value = "/zhi_pu_create_video")
    @Operation(summary = "智普AI 生成视频接口")
    public Resp<Object> zhiPuCreateVideo() {
        String urlImage = "https://pics1.baidu.com/feed/4034970a304e251f71aa6e49c7c97d077e3e5386.jpeg@f_auto?token=e4128a88d34b51bbe90cf61afd2b3b78";
        String model = "cogvideox-flash";
        String quality = "quality";
        String size = "1920x1080";
        int fps = 60;
        boolean withAudio = true;
        String requestId = "BU32490482323234";
        String prompt = "动画 1：“十一月 -” 重组（0-2 秒）\n" +
                        "初始：顶部 1/5 区域，“十”“一”“月” 3 块零散模糊。过程：0.5 秒起左到右移动（0.3 秒 / 块），到位闪烁，1.5 秒拼接，“-” 浮现。结束：“十一月 -” 固定，其余空白。\n" +
                        "动画 2：核心句拼接（2-4 秒）\n" +
                        "初始：“向任何方向！” 等 4 块在第 2/5 区域，透明度略高。过程：2 秒 “向任何方向！” 先到位，3 秒 “都”“是走向” 跟进，3.8 秒 “幸运！” 落下清晰。结束：上半部分文案完整，下半留碎片。\n" +
                        "动画 3：“安康 顺遂” 重组（4-6 秒）\n" +
                        "初始：两词块分处中层左右，轻微晃动。过程：4 秒弧形移动（0.5 秒 / 块），5 秒到位，5-6 秒渐清并浮现光斑。结束：中层文案固定，下层仍为碎片。\n" +
                        "动画 4：“快乐自由” 等拼接（6-8 秒）\n" +
                        "初始：3 块斜向排列，透明度 80%。过程：6 秒 “快乐自由” 先到位，7 秒 “财富” 切入，7.8 秒 “众如愿” 上移清晰。结束：仅底部署名留碎片。\n" +
                        "动画 5：署名收尾（8-10 秒）\n" +
                        "初始：署名 3 块在底部中央，90% 透明度闪烁。过程：8 秒 “@土豆文案馆” 左移，9 秒 “ώ” 旋转到位，9.8 秒全清，画面闪烁。结束：整体完整呈现，动画结束。";
        Object result = zhiPuAiProxyService.generationsVide(urlImage, model, quality, size, fps, withAudio, requestId, prompt);
        return Resp.ok(result);
    }

    @GetMapping(value = "/getVideoById")
    @Operation(summary = "智普AI 获取视频接口")
    public Resp<Object> getVideoById(@RequestParam("id") String id) {
        Object result = zhiPuAiProxyService.generationsVideById(id);
        return Resp.ok(result);
    }

}
